/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.improvement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.improvement.approval.AssessmentAuditService;
import com.koron.improvement.bean.Assessment;
import com.koron.improvement.bean.AssessmentHistory;
import com.koron.improvement.bean.AssessmentItem;
import com.koron.improvement.bean.AssessmentItemHistory;
import com.koron.improvement.mapper.AssessmentHistoryMapper;
import com.koron.improvement.mapper.AssessmentItemHistoryMapper;
import com.koron.improvement.mapper.AssessmentItemMapper;
import com.koron.improvement.mapper.AssessmentMapper;
import com.koron.improvement.service.api.AssessmentService;
import com.koron.improvement.utils.BaseEntityUtil;
import com.koron.improvement.utils.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AssessmentServiceImpl implements AssessmentService, AfterApprovalService, InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(AssessmentServiceImpl.class);

    @Value("${assessment_add_confirm}")
    private String assessmentAddConfirm;

    @Value("${assessment_discard_confirm}")
    private String assessmentDiscardConfirm;

    @Value("${assessment_edit_confirm}")
    private String assessmentEditConfirm;

    @Value("${assessment_approval_template_key}")
    private String assessmentApprovalTemplateKey;

    @Autowired
    private DictDataService dataService;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private Util util;

    @Autowired
    private FlowManagement flowManagement;


    void setProperties(Assessment assessment, AssessmentItemMapper assessmentItemMapper) {
        //获取字典表缓存
        Map<String, DictData> cacheMap = dataService.getCacheMap();
        if (assessment != null) {
            List<AssessmentItem> items = assessmentItemMapper.queryListByAssessmentId(assessment.getId());
            if (items != null && !items.isEmpty()) {
                items.stream().forEach(assessmentItem -> {
                    if (StringUtils.isNotBlank(assessmentItem.getItemId())) {
                        DictData item = cacheMap.get(assessmentItem.getItemId());
                        assessmentItem.setItemName(item != null ? item.getDictLabel() : "");
                    }
                });
            }
            assessment.setAssessmentItemList(items);
        }
    }

    @Override
    public MessageBean<?> queryList(Integer assessmentGrade, String deptName, Integer assessmentYear, Integer assessmentTimeType, Integer assessmentTimeValue, String corpName
            , Integer assessmentType, Integer page, Integer pageSize, String corpCode) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
            AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
            Integer start = null;
            if (page != null && page > 0 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            if (assessmentGrade == 1 && StringUtils.isBlank(corpCode)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_QUERY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_QUERY_CORPCODE.getDescription());
                return msg;
            }
            List<Assessment> list = mapper.queryList(assessmentGrade, deptName, assessmentYear, corpName, assessmentType, corpCode,
                    assessmentTimeType, assessmentTimeValue, start, pageSize);
            //获取itemList
            for (Assessment asm : list) {
                setProperties(asm, itemMapper);
            }
            int total = mapper.queryTotal(assessmentGrade, deptName, assessmentYear, corpName, assessmentType, corpCode,
                    assessmentTimeType, assessmentTimeValue);
            DataBean<Assessment> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> detail(String assessmentId) {
        MessageBean<Assessment> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Assessment.class);
        if (StringUtils.isBlank(assessmentId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
            AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
            Assessment assessment = mapper.selectByPrimaryKey(assessmentId);
            if (assessment == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            setProperties(assessment, itemMapper);
            msg.setData(assessment);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    MessageBean<?> checkAssessment(Assessment assessment) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (assessment == null) {
            msg.setCode(BusinessCode.ASSESSMENT_CAN_NOT_EMPTY.getCode());
            msg.setDescription(BusinessCode.ASSESSMENT_CAN_NOT_EMPTY.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(assessment.getTitle())) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_TITLE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_TITLE.getDescription());
            return msg;
        }
        if (assessment.getAssessmentType() == null) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_TYPE.getDescription());
            return msg;
        }

        if (StringUtils.isBlank(assessment.getCorpCode()) || StringUtils.isBlank(assessment.getCorpName())) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
            return msg;
        }
        if (assessment.getBenchmarkScore() == null || assessment.getDeductedScore() == null || assessment.getScore() == null) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_SCORE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_SCORE.getDescription());
            return msg;
        } else if (assessment.getBenchmarkScore() != (assessment.getDeductedScore() + assessment.getScore())) {
            msg.setCode(BusinessCode.ERROR_ASSESSMENT_SCORE.getCode());
            msg.setDescription(BusinessCode.ERROR_ASSESSMENT_SCORE.getDescription());
            return msg;
        }
        if (assessment.getAssessmentGrade() != 0 && (StringUtils.isBlank(assessment.getDeptName()) || StringUtils.isBlank(assessment.getDeptCode()))) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_DEPTCODE_NAME.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_DEPTCODE_NAME.getDescription());
            return msg;
        }
        if (assessment.getAssessmentYear() == null) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_YEAR.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_YEAR.getDescription());
            return msg;
        }
        if (assessment.getAssessmentTimeType() == null) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_TIME_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_TIME_TYPE.getDescription());
            return msg;
        } else if (assessment.getAssessmentTimeType() == 0) {
            //年
            assessment.setAssessmentTimeValue(assessment.getAssessmentYear());
        }
        if (assessment.getAssessmentTimeValue() == null && assessment.getAssessmentTimeType() != 0) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_TIME_VALUE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_TIME_VALUE.getDescription());
            return msg;
        }
        return msg;
    }

    AssessmentHistory translateAssessmentToHistory(Assessment assessment) throws Exception {
        AssessmentHistory history = new AssessmentHistory();
        history.setId(DefaultIdGenerator.getInstance().generateLongId());
        history.setBackupId(assessment.getId());
        history.setState(assessment.getState());
        history.setPreviewAttachment(assessment.getPreviewAttachment());
        history.setTitle(assessment.getTitle());
        history.setAssessmentTimeType(assessment.getAssessmentTimeType());
        history.setAssessmentGrade(assessment.getAssessmentGrade());
        history.setDeptCode(assessment.getDeptCode());
        history.setDeptName(assessment.getDeptName());
        history.setAssessmentTimeValue(assessment.getAssessmentTimeValue());
        history.setCorpName(assessment.getCorpName());
        history.setAssessmentType(assessment.getAssessmentType());
        history.setCorpCode(assessment.getCorpCode());
        history.setAssessmentYear(assessment.getAssessmentYear());
        history.setBenchmarkScore(assessment.getBenchmarkScore());
        history.setDeductedScore(assessment.getDeductedScore());
        history.setScore(assessment.getScore());
        history.setRemark(assessment.getRemark());
        history.setAttachment(assessment.getAttachment());
        history.setAddUser(assessment.getAddUser());
        history.setUpdateUser(assessment.getUpdateUser());
        history.setAddTime(assessment.getAddTime());
        history.setUpdateTime(assessment.getUpdateTime());
        history.setAddUserName(assessment.getAddUserName());
        history.setUpdateUserName(assessment.getUpdateUserName());
        return history;
    }

    List<AssessmentItemHistory> translateItemListToHistory(List<AssessmentItem> items, String assessmentId) throws Exception {
        List<AssessmentItemHistory> historyList = new ArrayList<>();
        if (items == null || items.isEmpty()) {
            return null;
        }
        for (AssessmentItem item : items) {
            AssessmentItemHistory history = new AssessmentItemHistory();
            history.setAssessmentId(assessmentId);
            history.setItemName(item.getItemName());
            history.setItemId(item.getItemId());
            history.setDeductedScore(item.getDeductedScore());
            history.setDeductedReason(item.getDeductedReason());
            history.setAddUser(item.getAddUser());
            history.setUpdateUser(item.getUpdateUser());
            history.setAddTime(item.getAddTime());
            history.setUpdateTime(item.getUpdateTime());
            history.setAddUserName(item.getAddUserName());
            history.setUpdateUserName(item.getUpdateUserName());
            history.setId(DefaultIdGenerator.getInstance().generateLongId());
            historyList.add(history);
        }
        return historyList;
    }


    @Override
    public MessageBean<?> saveOrCommit(String assessmentItemListStr, MultipartFile[] files,
                                       String userCode, StaffBean user,
                                       String approverCodeListStr, String assessmentStr, Integer operationType) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        List<String> filePaths = new ArrayList<>();
        List<String> filePrePaths = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
            AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
            AssessmentHistoryMapper assessmentHistoryMapper = factory.getMapper(AssessmentHistoryMapper.class);
            AssessmentItemHistoryMapper assessmentItemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
            Assessment assessment = JSONObject.parseObject(assessmentStr, Assessment.class);
            MessageBean<?> messageBean = checkAssessment(assessment);
            if (messageBean.getCode() != 0) {
                factory.close();
                return messageBean;
            }
            if (StringUtils.isBlank(assessmentItemListStr)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getDescription());
                factory.close();
                return msg;
            }

            boolean addFlag = true;
            if (StringUtils.isBlank(assessment.getId())) {
                BaseEntityUtil.setAddBaseProperties(assessment, user);
            } else {
                Assessment assessmentOrg = mapper.selectByPrimaryKey(assessment.getId());
                if (assessmentOrg == null) {
                    BaseEntityUtil.setAddBaseProperties(assessment, user);
                } else if (assessmentOrg.getState() == 5) {
                    BaseEntityUtil.setUpdateBaseProperties(assessment, user);
                    addFlag = false;
                } else {
                    msg.setCode(BusinessCode.CAN_NOT_OPERATION.getCode());
                    msg.setDescription(BusinessCode.CAN_NOT_OPERATION.getDescription());
                    factory.close(false);
                    return msg;
                }
            }
            List<AssessmentItem> items = JSONObject.parseArray(assessmentItemListStr, AssessmentItem.class);
            if (items == null || items.size() <= 0) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getDescription());
                factory.close();
                return msg;
            }
            double deScore = 0;
            for (AssessmentItem item : items) {
                if (StringUtils.isBlank(item.getItemId())) {
                    msg.setCode(BusinessCode.EMPTY_ITEM_ID.getCode());
                    msg.setDescription(BusinessCode.EMPTY_ITEM_ID.getDescription());
                    factory.close();
                    return msg;
                }
                if (item.getDeductedScore() == null) {
                    item.setDeductedScore(0.0);
                }
                deScore += item.getDeductedScore();
                item.setAssessmentId(assessment.getId());
                BaseEntityUtil.setAddBaseProperties(item, user);
            }
            if (deScore != assessment.getDeductedScore()) {
                msg.setCode(BusinessCode.ERROR_ASSESSMENT_SCORE.getCode());
                msg.setDescription(BusinessCode.ERROR_ASSESSMENT_SCORE.getDescription());
                factory.close();
                return msg;
            }
            //保存附件；
            List<String> keepAddressList = new ArrayList<>();
            List<String> keepPreAddressList = new ArrayList<>();
            if (StringUtils.isNotBlank(assessment.getKeepPathListStr())) {
                String[] keepAddressArray = assessment.getKeepPathListStr().split("[,，]");
                keepAddressList.addAll(Arrays.asList(keepAddressArray));
            }
            if (StringUtils.isNotBlank(assessment.getKeepPrePathListStr())) {
                String[] keepPreAddressArray = assessment.getKeepPrePathListStr().split("[,，]");
                keepPreAddressList.addAll(Arrays.asList(keepPreAddressArray));
            }
            if (files != null && files.length > 0) {
                for (MultipartFile f : files) {
                    if (f != null) {
                        String url = clientWrapper.uploadFile(f);
                        String filPath = url + "#" + f.getOriginalFilename();
                        keepAddressList.add(filPath);
                        filePaths.add(filPath);
                        String pdfPath = docConverterUtils.converterUpdate(f);
                        if (pdfPath != null) {
                            keepPreAddressList.add(pdfPath);
                            filePrePaths.add(pdfPath);
                        } else {
                            keepPreAddressList.add(null);
                        }
                    }
                }
            }
            assessment.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
            assessment.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
            //保存评估考核审核记录
            if (operationType == 0) {
                assessment.setState(5);
            } else {
                assessment.setState(1);
            }
            if (addFlag) {
                mapper.insert(assessment);
            } else {
                mapper.updateByPrimaryKeySelective(assessment);
                itemMapper.deleteByAssessmentId(assessment.getId());
            }
            if (items != null && !items.isEmpty()) {
                itemMapper.insertList(items);
            }
            if (operationType == 1) {
                if (StringUtils.isBlank(approverCodeListStr)) {
                    msg.setCode(BusinessCode.EMPTY_APPROVER_LIST.getCode());
                    msg.setDescription(BusinessCode.EMPTY_APPROVER_LIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
                if (approverCodeList == null || approverCodeList.isEmpty()) {
                    msg.setCode(BusinessCode.EMPTY_APPROVER_LIST.getCode());
                    msg.setDescription(BusinessCode.EMPTY_APPROVER_LIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                AssessmentHistory history = translateAssessmentToHistory(assessment);
                assessmentHistoryMapper.insert(history);
                if (items != null && !items.isEmpty()) {
                    List<AssessmentItemHistory> historyList = translateItemListToHistory(items, history.getId());
                    assessmentItemHistoryMapper.insertList(historyList);
                }

                // 构造audit
                Audit audit = new Audit();
                Date now = new Date();
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setUpdateUser(user.getName());
                audit.setUpdateTime(now);
                audit.setAddUser(user.getName());
                audit.setAddTime(now);
                audit.setFlowType(1);
                audit.setOperation(1);
                audit.setTarget(AssessmentAuditService.class.getName());
                audit.setFlowName(assessmentAddConfirm);
                audit.setTitle(assessmentAddConfirm);
                audit.setCorpCode(history.getCorpCode());
                audit.setInitiatorCode(user.getName());
                audit.setDescription(assessmentAddConfirm);
                audit.setState(1);
                audit.setTemplateKey(assessmentApprovalTemplateKey);
                audit.setSetCode("institution_manage");
                audit.setInitiatorAccount(user.getUserid());
                List<String> idList = new ArrayList<>();
                idList.add(history.getId());
                audit.setBusinessIds(new Gson().toJson(idList));
                Map<String, Object> businessMap = new HashMap<>();
                StringBuilder codes = new StringBuilder();
                for (String code : approverCodeList) {
                    codes.append(code.split("_")[0]).append(",");
//                    codes.append("1-").append(code.split("_")[0]).append(",");
                }
                businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
                if (!flowManagement.initFlow(user, audit, businessMap)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("提交考核评估失败");
                } else {
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("提交考核评估成功");
                }
            }
            if (StringUtils.isNotEmpty(assessment.getDeletePathListStr())) {
                String[] delArray = assessment.getDeletePathListStr().split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
            if (StringUtils.isNotEmpty(assessment.getDeletePrePathListStr())) {
                String[] delArray = assessment.getDeletePrePathListStr().split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            if (filePaths != null && !filePaths.isEmpty()) {
                for (String p : filePaths) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            if (filePrePaths != null && !filePrePaths.isEmpty()) {
                for (String p : filePrePaths) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> updateAssessment(String assessmentItemListStr, MultipartFile[] files, StaffBean user,
                                           String userCode, String approverCodeListStr, String assessmentStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);


        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
        if (approverCodeList == null || approverCodeList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_APPROVER_LIST.getCode());
            msg.setDescription(BusinessCode.EMPTY_APPROVER_LIST.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        List<String> filePaths = new ArrayList<>();
        List<String> filePrePaths = new ArrayList<>();
        try {
            Assessment assessment = JSONObject.parseObject(assessmentStr, Assessment.class);
            if (assessment == null) {
                msg.setCode(BusinessCode.ASSESSMENT_CAN_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_CAN_NOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(assessment.getId())) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_ID.getDescription());
                return msg;
            }
            AssessmentMapper assessmentMapper = factory.getMapper(AssessmentMapper.class);
            AssessmentHistoryMapper assessmentHistoryMapper = factory.getMapper(AssessmentHistoryMapper.class);
            AssessmentItemHistoryMapper assessmentItemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
            Assessment assessmentOld = assessmentMapper.selectByPrimaryKey(assessment.getId());
            if (assessmentOld == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            MessageBean<?> messageBean = checkAssessment(assessment);
            if (messageBean.getCode() != 0) {
                factory.close();
                return messageBean;
            }
            if (StringUtils.isBlank(assessmentItemListStr)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getDescription());
                factory.close();
                return msg;
            }
            BaseEntityUtil.setUpdateBaseProperties(assessment, user);
            List<AssessmentItem> items = JSONObject.parseArray(assessmentItemListStr, AssessmentItem.class);
            if (items == null || items.size() <= 0) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_ITEM_lIST.getDescription());
                factory.close();
                return msg;
            }
            double deScore = 0;
            for (AssessmentItem item : items) {
                if (StringUtils.isBlank(item.getItemId())) {
                    msg.setCode(BusinessCode.EMPTY_ITEM_ITEM_ID.getCode());
                    msg.setDescription(BusinessCode.EMPTY_ITEM_ITEM_ID.getDescription());
                    factory.close();
                    return msg;
                }
                if (item.getDeductedScore() == null) {
                    item.setDeductedScore(0.0);
                }
                deScore += item.getDeductedScore();
//                item.setAssessmentId(assessment.getId());
                BaseEntityUtil.setAddBaseProperties(item, user);
            }
            if (deScore != assessment.getDeductedScore()) {
                msg.setCode(BusinessCode.ERROR_ASSESSMENT_SCORE.getCode());
                msg.setDescription(BusinessCode.ERROR_ASSESSMENT_SCORE.getDescription());
                factory.close();
                return msg;
//                assessment.setScore(assessment.getBenchmarkScore() - deScore);
            }
            //保存附件
            String[] keepAddressArray = StringUtils.isEmpty(assessment.getKeepPathListStr()) ? null : assessment.getKeepPathListStr().split("[,，]");
            String[] keepPreAddressArray = StringUtils.isEmpty(assessment.getKeepPrePathListStr()) ? null : assessment.getKeepPrePathListStr().split("[,，]");
            List<String> keepAddressList = new ArrayList<>();
            List<String> keepPreAddressList = new ArrayList<>();
            if (keepAddressArray != null && keepAddressArray.length > 0) {
                keepAddressList = Arrays.asList(keepAddressArray).stream().collect(Collectors.toList());
            }
            if (keepPreAddressArray != null && keepPreAddressArray.length > 0) {
                keepPreAddressList = Arrays.asList(keepPreAddressArray).stream().collect(Collectors.toList());
            }
            if (files != null && files.length > 0) {
                for (MultipartFile file : files) {
                    if (file != null) {
                        String url = clientWrapper.uploadFile(file);
                        String filPath = url + "#" + file.getOriginalFilename();
                        keepAddressList.add(filPath);
                        filePaths.add(filPath);
                        //doc转换pdf文件并存储
                        String pdfPath = docConverterUtils.converterUpdate(file);
                        if (pdfPath != null) {
                            keepPreAddressList.add(pdfPath);
                            filePrePaths.add(pdfPath);
                        } else {
                            keepPreAddressList.add(filPath);
                        }
                    }
                }
            }
            assessment.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
            assessment.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
            //保存评估考核
            assessmentOld.setState(2);
            assessmentMapper.updateByPrimaryKeySelective(assessmentOld);
            assessment.setState(2);
            assessment.setAddTime(assessmentOld.getAddTime());
            assessment.setAddUser(assessmentOld.getAddUser());
            assessment.setAddUserName(assessmentOld.getAddUserName());
            AssessmentHistory history = translateAssessmentToHistory(assessment);
            assessmentHistoryMapper.insert(history);

            if (items != null && !items.isEmpty()) {
                List<AssessmentItemHistory> historyList = translateItemListToHistory(items, history.getId());
                assessmentItemHistoryMapper.insertList(historyList);
            }

            // 构造audit
            Audit audit = new Audit();
            Date now = new Date();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(1);
            audit.setTarget(AssessmentServiceImpl.class.getName());
            audit.setFlowName(assessmentEditConfirm);
            audit.setTitle(assessmentEditConfirm);
            audit.setCorpCode(history.getCorpCode());
            audit.setInitiatorCode(user.getCode());
            audit.setDescription(assessmentEditConfirm);
            audit.setState(1);
            audit.setTemplateKey(assessmentApprovalTemplateKey);
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            List<String> idList = new ArrayList<>();
            idList.add(history.getId());
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append(code.split("_")[0]).append(",");
//                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交考核评估失败");
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("提交考核评估成功");
            }
            if (StringUtils.isNotEmpty(assessment.getDeletePathListStr())) {
                String[] delArray = assessment.getDeletePathListStr().split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
            if (StringUtils.isNotEmpty(assessment.getDeletePrePathListStr())) {
                String[] delArray = assessment.getDeletePrePathListStr().split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
        } catch (Exception e) {
            if (filePaths != null && !filePaths.isEmpty()) {
                for (String p : filePaths) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            if (filePrePaths != null && !filePrePaths.isEmpty()) {
                for (String p : filePrePaths) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public List<Assessment> getExportList(Integer assessmentGrade, String deptName, Integer assessmentTimeType, Integer assessmentTimeValue, Integer assessmentYear,
                                          String corpName, Integer assessmentType, String corpCode) {
        try (SessionFactory factory = new SessionFactory()) {
            AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
            AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
            if (assessmentGrade == 1 && StringUtils.isBlank(corpCode)) {
                return null;
            }
            List<Assessment> list = mapper.queryList(assessmentGrade, deptName, assessmentYear, corpName, assessmentType, corpCode, assessmentTimeType, assessmentTimeValue, null, null);
            //获取itemList
            for (Assessment asm : list) {
                setProperties(asm, itemMapper);
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<?> importFromExcel(MultipartFile file, StaffBean user, Integer assessmentGrade, Integer assessmentType, String corpCode, String approverCodeListStr) {
        Map<Assessment, List<AssessmentItem>> map = new HashMap<>();
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
        if (approverCodeList == null || approverCodeList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_APPROVER_LIST.getCode());
            msg.setDescription(BusinessCode.EMPTY_APPROVER_LIST.getDescription());
            return msg;
        }
        try {
            //先将文件上传到文件服务器
            if (null == file) {
                msg.setCode(22001);
                msg.setDescription("上传文件为空");
                return msg;
            }
            String fileName = file.getOriginalFilename();
            String filePath = clientWrapper.uploadFile(file) + "#" + fileName;//文件上传的路径

            //处理excel中的内容
            InputStream inputStream = file.getInputStream();

            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            if (null == workbook) {
                logger.error("上传文件为空");
                msg.setCode(BusinessCode.EMPTY_FILE.getCode());
                msg.setDescription(BusinessCode.EMPTY_FILE.getDescription());
                return msg;
            }
            XSSFSheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                logger.error("上传文件为空");
                msg.setCode(BusinessCode.EMPTY_FILE.getCode());
                msg.setDescription(BusinessCode.EMPTY_FILE.getDescription());
                return msg;
            }
            List<CellRangeAddress> combineCell = getCombineCell(sheet);
            int rowsNumm = sheet.getPhysicalNumberOfRows();
            for (int i = 2; i < rowsNumm; ) {
                XSSFRow row = sheet.getRow(i);
                // 合并了多行，取合并后单元格范围信息
                CellRangeAddress cellRange = getCellRange(combineCell, row.getCell(1));
                int lastRow = i;
                if (cellRange != null) {
                    lastRow = cellRange.getLastRow();
                }
                List<XSSFRow> rows = new ArrayList<>();
                while (lastRow >= i) {
                    rows.add(sheet.getRow(i));
                    i++;
                }
                parseRows(rows, map, user, assessmentGrade, assessmentType, corpCode);
            }
            distinguishAndPersistence(filePath, user, map, corpCode, approverCodeList);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FILE_UPLOAD_ERROR.getCode());
            msg.setDescription(BusinessCode.FILE_UPLOAD_ERROR.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> delete(StaffBean user, String assessmentId, String approverCodeListStr) {
        Map<Assessment, List<AssessmentItem>> map = new HashMap<>();
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }

        SessionFactory factory = new SessionFactory();
        try {
            AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
            AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
            AssessmentHistoryMapper assessmentHistoryMapper = factory.getMapper(AssessmentHistoryMapper.class);
            AssessmentItemHistoryMapper assessmentItemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);

            if (StringUtils.isBlank(assessmentId)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_ID.getDescription());
                return msg;
            }
            Assessment assessment = mapper.selectByPrimaryKey(assessmentId);
            if (assessment == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            if (assessment.getState() == 5) {
                mapper.deleteByPrimaryKey(assessment.getId());
                itemMapper.deleteByAssessmentId(assessment.getId());
                return msg;
            }
            List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
            if (approverCodeList == null || approverCodeList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_APPROVER_LIST.getCode());
                msg.setDescription(BusinessCode.EMPTY_APPROVER_LIST.getDescription());
                return msg;
            }
            List<AssessmentItem> itemList = itemMapper.queryListByAssessmentId(assessment.getId());
            assessment.setState(3);
            mapper.updateByPrimaryKeySelective(assessment);
            AssessmentHistory history = translateAssessmentToHistory(assessment);
            assessmentHistoryMapper.insert(history);
            if (itemList != null && !itemList.isEmpty()) {
                List<AssessmentItemHistory> itemHistoryList = translateItemListToHistory(itemList, history.getId());
                assessmentItemHistoryMapper.insertList(itemHistoryList);
            }
            // 构造audit
            Audit audit = new Audit();
            Date now = new Date();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(2);
            audit.setTarget(AssessmentServiceImpl.class.getName());
            audit.setFlowName(assessmentDiscardConfirm);
            audit.setTitle(assessmentDiscardConfirm);
            audit.setCorpCode(user.getDepartmentCode());
            audit.setInitiatorCode(user.getCode());
            audit.setDescription(assessmentDiscardConfirm);
            audit.setState(1);
            audit.setTemplateKey(assessmentApprovalTemplateKey);
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            List<String> idList = new ArrayList<>();
            idList.add(history.getId());
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append(code.split("_")[0]).append(",");
//                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交考核评估失败");
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("提交考核评估成功");
            }

            if (StringUtils.isNotEmpty(assessment.getAttachment())) {
                String[] delArray = assessment.getAttachment().split("[,，]");
                for (String att : delArray) {
                    clientWrapper.deleteFile(att.split("#")[0]);
                }
            }
            if (StringUtils.isNotEmpty(assessment.getPreviewAttachment())) {
                String[] delArray = assessment.getPreviewAttachment().split("[,，]");
                for (String att : delArray) {
                    clientWrapper.deleteFile(att.split("#")[0]);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FILE_UPLOAD_ERROR.getCode());
            msg.setDescription(BusinessCode.FILE_UPLOAD_ERROR.getDescription());
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }


    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
                    Map<String, DictData> cacheMap = dataService.getCacheMap();
                    AssessmentHistoryMapper historyMapper = factory.getMapper(AssessmentHistoryMapper.class);
                    AssessmentItemHistoryMapper itemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
                    List<AssessmentHistory> historyList = historyMapper.queryByIdList(idList);
                    if (historyList != null && !historyList.isEmpty()) {
                        for (AssessmentHistory history : historyList) {
                            if (history != null) {
                                List<AssessmentItemHistory> itemHistoryList = itemHistoryMapper.queryListByAssessmentId(history.getId());
                                if (itemHistoryList != null && !itemHistoryList.isEmpty()) {
                                    itemHistoryList.stream().forEach(itemHistory -> {
                                        if (StringUtils.isNotBlank(itemHistory.getItemId())) {
                                            DictData item = cacheMap.get(itemHistory.getItemId());
                                            itemHistory.setItemName(item != null ? item.getDictLabel() : "");
                                        }
                                    });
                                }
                                history.setAssessmentItemHistoryList(itemHistoryList);
                            }
                        }
                    }
                    msg.setData(historyList);
                } else {
                    msg.setCode(20990);
                    msg.setDescription("审批业务数据id不能为空");
                    return msg;
                }
            } else {
                msg.setCode(20990);
                msg.setDescription("审批业务数据id不能为空");
                return msg;
            }
        } catch (Exception e) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    //具体业务基本都在此方法执行
    @SuppressWarnings("unchecked")
    private void distinguishAndPersistence(String filePath, StaffBean user,
                                           Map<Assessment, List<AssessmentItem>> map, String corpCode,
                                           List<String> approverCodeList) {
        MessageBean<?> msg = new MessageBean<>();
        List<Assessment> beanList = new ArrayList<>();
        for (Map.Entry<Assessment, List<AssessmentItem>> entry : map.entrySet()) {
            Assessment assessment = entry.getKey();
            List<AssessmentItem> itemList = entry.getValue();
            if (itemList == null || itemList.isEmpty()) {
                continue;
            }
            assessment.setAssessmentItemList(itemList);
            beanList.add(assessment);
        }
        SessionFactory factory = new SessionFactory();
        List<String> idList = new ArrayList<>();

        try {
            AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
            AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
            AssessmentHistoryMapper assessmentHistoryMapper = factory.getMapper(AssessmentHistoryMapper.class);
            AssessmentItemHistoryMapper assessmentItemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);

            for (Assessment assessment : beanList) {
                if (assessment != null) {
                    assessment.setId(null);
                    AssessmentHistory history = translateAssessmentToHistory(assessment);
                    assessmentHistoryMapper.insert(history);
                    idList.add(history.getId());
                    List<AssessmentItem> itemList = assessment.getAssessmentItemList();
//                    mapper.insert(assessment);
                    if (itemList != null && !itemList.isEmpty()) {
                        List<AssessmentItemHistory> historyList = translateItemListToHistory(itemList, history.getId());
                        assessmentItemHistoryMapper.insertList(historyList);
                    }
                }
            }
            // 构造audit
            Audit audit = new Audit();
            Date now = new Date();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(1);
            audit.setTarget(AssessmentAuditService.class.getName());
            audit.setFlowName(assessmentDiscardConfirm);
            audit.setTitle(assessmentDiscardConfirm);
            audit.setCorpCode(corpCode);
            audit.setInitiatorCode(user.getCode());
            audit.setDescription(assessmentDiscardConfirm);
            audit.setState(1);
            audit.setTemplateKey(assessmentApprovalTemplateKey);
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append(code.split("_")[0]).append(",");
//                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交考核评估失败");
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("提交考核评估成功");
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (StringUtils.isNotBlank(filePath)) {
                clientWrapper.deleteFile(filePath.split("#")[0]);
            }
            factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    // 单个考核评估和多个扣分项
    private String parseRows(List<XSSFRow> rows, Map<Assessment, List<AssessmentItem>> map, StaffBean user,
                             Integer assessmentGrade, Integer assessmentType, String corpCode) {
        Assessment assessment = null;
        List<AssessmentItem> itemList = new ArrayList<>();
        StringBuilder description = new StringBuilder();
        List<DepartmentTreeBean> deptList = null;
        if (assessmentGrade == 1) {
            deptList = (List<DepartmentTreeBean>) util.depttree(corpCode, 0).getData();
        }
        List<CorpBean> corpList = null;
        if (assessmentType != 0) {
            //获取公司列表返回公司列表根据name获取code
            MessageBean<DataBean<CorpBean>> beanMessageBean = corpManagementService.corpList(null, null, null);
            if (beanMessageBean.getCode() == 0 && beanMessageBean.getData() != null) {
                DataBean<CorpBean> dataBean = beanMessageBean.getData();
                if (dataBean != null && dataBean.getList() != null) {
                    corpList = dataBean.getList();
                }
            }
        }
        List<DictData> elementList = getElementList();
        for (int i = 0; i < rows.size(); i++) {
            if (i == 0) {
                assessment = parseAssessment(rows.get(i), user, assessmentGrade, assessmentType, corpCode, deptList, corpList);
                if (assessment == null) {
                    return null;
                }
            }
            AssessmentItem item = parseAssessmentItem(rows.get(i), user, elementList, assessment.getId());
            if (item != null) {
                itemList.add(item);
            }
        }
        double deScore = itemList.stream().mapToDouble(AssessmentItem::getDeductedScore).sum();
        if (assessment.getDeductedScore() == null || deScore != assessment.getDeductedScore()) {
            assessment.setDeductedScore(deScore);
        }
        if (assessment.getScore() == null || assessment.getScore() != (assessment.getBenchmarkScore() - assessment.getDeductedScore())) {
            assessment.setScore(assessment.getBenchmarkScore() - assessment.getDeductedScore());
        }
        map.put(assessment, itemList);
        return description.toString();
    }

    private List<DictData> getElementList() {
        try (SessionFactory factory = new SessionFactory()) {
            DictDataMapper mapper = factory.getMapper(DictDataMapper.class);
            return mapper.queryAll(null, "firstElement", null, null);
        } catch (Exception e) {
            return null;
        }
    }


    private Assessment parseAssessment(XSSFRow row, StaffBean user, Integer assessmentGrade, Integer assessmentType,
                                       String corpCode, List<DepartmentTreeBean> deptList, List<CorpBean> corpList) {
        Assessment assessment = new Assessment();
        try (SessionFactory factory = new SessionFactory()) {
            String name = getCellValue(row.getCell(0));
            String yearStr = getCellValue(row.getCell(1));
            String timeType = getCellValue(row.getCell(2));
            String timeValue = getCellValue(row.getCell(3));
            String benchmarkScoreStr = getCellValue(row.getCell(4));
            String deductedScoreStr = getCellValue(row.getCell(5));
            String scoreStr = getCellValue(row.getCell(6));
            String remark = getCellValue(row.getCell(7));

            Integer year = StringUtils.isBlank(yearStr) ? null : (int) Double.parseDouble(yearStr);

            Integer type = null;

            if ("年度".equals(timeType)) {
                type = 0;
            } else if ("季度".equals(timeType)) {
                type = 1;
            } else if ("月度".equals(timeType)) {
                type = 2;
            }
            Integer value = StringUtils.isBlank(timeValue) ? null : (int) Double.parseDouble(timeValue);


            Double benchmarkScore = StringUtils.isBlank(benchmarkScoreStr) ? null : Double.parseDouble(benchmarkScoreStr);
            Double deductedScore = StringUtils.isBlank(deductedScoreStr) ? null : Double.parseDouble(deductedScoreStr);
            Double score = StringUtils.isBlank(scoreStr) ? null : Double.parseDouble(scoreStr);

            if (assessmentType == null) {
                return null;
            }

            if (assessmentGrade == null) {
                return null;
            }
            if (StringUtils.isBlank(name) && assessmentType != 0) {
                return null;
            }

            if (year == null) {
                return null;
            }
            if (type == null) {
                return null;
            }
            if (value == null && type != 0) {
                return null;
            }
            if (benchmarkScore == null) {
                return null;
            }

            //处理公司
            if (assessmentType == 0) {
                //自评需验证是否为登录人本公司
                MessageBean<DepartmentTreeBean> retMsg = (MessageBean<DepartmentTreeBean>) util.corp(corpCode);
                if (retMsg != null) {
                    DepartmentTreeBean bean = retMsg.getData();
                    if (bean == null) {
                        return null;
                    }
                    if (!name.equals(bean.getName())) {
                        return null;
                    }
                    assessment.setCorpName(name);
                    assessment.setCorpCode(bean.getDepartmentCode());
                } else {
                    return null;
                }
            } else {
                //获取公司列表返回公司列表根据name获取code
                if (corpList != null && corpList.size() > 0) {
                    corpList.stream().forEach(l -> {
                        if (name.equals(l.getCorpName())) {
                            assessment.setCorpCode(l.getCorpCode());
                            assessment.setCorpName(l.getCorpName());
                        }
                    });
                } else {
                    return null;
                }
            }

            //处理部门
            if (assessmentGrade != 1) {
                assessmentGrade = 0;
                //根据名称查
                assessment.setAssessmentGrade(assessmentGrade);

            } else {
                assessment.setAssessmentGrade(assessmentGrade);
                if (deptList != null) {
                    deptList.stream().forEach(dept -> {
                        if (name.equals(dept.getName())) {
                            assessment.setDeptCode(dept.getDepartmentCode());
                            assessment.setDeptName(dept.getName());
                        }
                    });
                }
                if (assessment.getDeptCode() == null || assessment.getDeptName() == null) {
                    return null;
                }
            }
            assessment.setAssessmentType(assessmentType);
            assessment.setAssessmentTimeType(type);
            assessment.setAssessmentTimeValue(value);
            assessment.setAssessmentYear(year);
            assessment.setBenchmarkScore(benchmarkScore);
            assessment.setDeductedScore(deductedScore);
            assessment.setScore(score);
            assessment.setRemark(remark);
            BaseEntityUtil.setAddBaseProperties(assessment, user);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
        return assessment;
    }

    private AssessmentItem parseAssessmentItem(XSSFRow row, StaffBean user, List<DictData> elementList, String assessmentId) {
        try {
            AssessmentItem item = new AssessmentItem();
            String elementName = getCellValue(row.getCell(7));
            String deductedScoreStr = getCellValue(row.getCell(8));
            String deductedReason = getCellValue(row.getCell(9));

            String elementId = null;
            Double deductedScore = StringUtils.isBlank(deductedScoreStr) ? null : Double.parseDouble(deductedScoreStr);
            if (StringUtils.isBlank(elementName)) {
                return null;
            }
            DictData dictData = getElementFromList(elementName, elementList);
            if (dictData == null) {
                return null;
            }
            item.setItemId(dictData.getId());
            item.setItemName(elementName);
            item.setDeductedScore(deductedScore);
            item.setDeductedReason(deductedReason);
            item.setAssessmentId(assessmentId);
            BaseEntityUtil.setAddBaseProperties(item, user);
            return item;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    private DictData getElementFromList(String elementName, List<DictData> elementList) {
        if (StringUtils.isBlank(elementName) || elementList == null || elementList.isEmpty()) {
            return null;
        }
        List<DictData> resultList = elementList.stream().filter(dept -> {
            return elementName.equals(dept.getDictLabel());
        }).collect(Collectors.toList());
        if (resultList != null && resultList.size() > 0) {
            return resultList.get(0);
        }
        return null;
    }

    /**
     * 获取合并单元格的范围
     *
     * @param listCombineCell
     * @param cell
     * @return
     */
    private CellRangeAddress getCellRange(List<CellRangeAddress> listCombineCell, XSSFCell cell) {
        int firstC = 0, lastC = 0, firstR = 0, lastR = 0;
        for (CellRangeAddress ca : listCombineCell) {
            // 获得合并单元格的起始行, 结束行, 起始列, 结束列
            firstC = ca.getFirstColumn();
            lastC = ca.getLastColumn();
            firstR = ca.getFirstRow();
            lastR = ca.getLastRow();
            if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
                if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
                    return ca;
                }
            }
        }
        return null;
    }

    /**
     * 合并单元格处理,获取合并行
     *
     * @param sheet
     * @return List<CellRangeAddress>
     */
    public List<CellRangeAddress> getCombineCell(XSSFSheet sheet) {
        List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
        // 获得一个 sheet 中合并单元格的数量
        int sheetmergerCount = sheet.getNumMergedRegions();
        // 遍历所有的合并单元格
        for (int i = 0; i < sheetmergerCount; i++) {
            // 获得合并单元格保存进list中
            CellRangeAddress ca = sheet.getMergedRegion(i);
            list.add(ca);
        }
        return list;
    }

    /**
     * 获取单元格的值
     *
     * @param cell
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getCellValue(XSSFCell cell) {
        if (cell == null)
            return "";
        if (cell.getCellTypeEnum() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return "";
        }
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        AssessmentHistoryMapper historyMapper = factory.getMapper(AssessmentHistoryMapper.class);
                        AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
                        AssessmentItemHistoryMapper itemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
                        AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
                        AssessmentHistory history = historyMapper.selectByPrimaryKey(planId);
                        List<AssessmentItemHistory> itemHistoryList = itemHistoryMapper.queryListByAssessmentId(history.getId());
                        if (history != null) {
                            history.setState(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                            Assessment assessmentOld = mapper.selectByPrimaryKey(history.getBackupId());

                            if (assessmentOld != null) {
                                Assessment assessmentNew = translateHistoryToAssessment(history);
                                assessmentNew.setId(assessmentOld.getId());
//                            mapper.insert(assessmentNew);
                                mapper.updateByPrimaryKeySelective(assessmentNew);
                                itemMapper.deleteByAssessmentId(assessmentNew.getId());
                                if (itemHistoryList != null && !itemHistoryList.isEmpty()) {
                                    List<AssessmentItem> itemList = translateHistoryToItemList(itemHistoryList, assessmentNew.getId());
                                    itemMapper.insertList(itemList);
                                }
                            }
//                            AssessmentHistory assessmentOldHistory = translateAssessmentToHistory(assessmentOld);
//                            assessmentOldHistory.setState(0);
//                            List<AssessmentItem> assessmentOldItemList = itemMapper.queryListByAssessmentId(assessmentOld.getId());
//                            List<AssessmentItemHistory> assessmentOldItemHistoryList=translateItemListToHistory(assessmentOldItemList,assessmentOldHistory.getId());

                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    private void editApprovalDiscard(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        AssessmentHistoryMapper historyMapper = factory.getMapper(AssessmentHistoryMapper.class);
                        AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
                        AssessmentItemHistoryMapper itemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
                        AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
                        AssessmentHistory history = historyMapper.selectByPrimaryKey(planId);
//                        List<AssessmentItemHistory> itemHistoryList = itemHistoryMapper.queryListByAssessmentId(history.getId());
                        if (history != null) {
                            history.setState(4);
                            historyMapper.updateByPrimaryKeySelective(history);
                            Assessment assessmentOld = mapper.selectByPrimaryKey(history.getBackupId());
                            if (assessmentOld != null) {
                                assessmentOld.setState(0);
                                mapper.updateByPrimaryKeySelective(assessmentOld);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    Assessment translateHistoryToAssessment(AssessmentHistory history) throws Exception {
        Assessment assessment = new Assessment();
        assessment.setId(DefaultIdGenerator.getInstance().generateLongId());
        assessment.setState(history.getState());
        assessment.setPreviewAttachment(history.getPreviewAttachment());
        assessment.setTitle(history.getTitle());
        assessment.setAssessmentTimeType(history.getAssessmentTimeType());
        assessment.setAssessmentGrade(history.getAssessmentGrade());
        assessment.setDeptCode(history.getDeptCode());
        assessment.setDeptName(history.getDeptName());
        assessment.setAssessmentTimeValue(history.getAssessmentTimeValue());
        assessment.setCorpName(history.getCorpName());
        assessment.setAssessmentType(history.getAssessmentType());
        assessment.setCorpCode(history.getCorpCode());
        assessment.setAssessmentYear(history.getAssessmentYear());
        assessment.setBenchmarkScore(history.getBenchmarkScore());
        assessment.setDeductedScore(history.getDeductedScore());
        assessment.setScore(history.getScore());
        assessment.setRemark(history.getRemark());
        assessment.setAttachment(history.getAttachment());
        assessment.setAddUser(history.getAddUser());
        assessment.setUpdateUser(history.getUpdateUser());
        assessment.setAddTime(history.getAddTime());
        assessment.setUpdateTime(history.getUpdateTime());
        assessment.setAddUserName(history.getAddUserName());
        assessment.setUpdateUserName(history.getUpdateUserName());
        return assessment;
    }

    List<AssessmentItem> translateHistoryToItemList(List<AssessmentItemHistory> historyList, String assessmentId) throws Exception {
        List<AssessmentItem> items = new ArrayList<>();
        if (historyList == null || historyList.isEmpty()) {
            return null;
        }
        for (AssessmentItemHistory history : historyList) {
            AssessmentItem item = new AssessmentItem();
//            BeanUtils.copyProperties(item, history);
            item.setItemName(history.getItemName());
            item.setItemId(history.getItemId());
            item.setDeductedScore(history.getDeductedScore());
            item.setDeductedReason(history.getDeductedReason());
            item.setAddUser(history.getAddUser());
            item.setUpdateUser(history.getUpdateUser());
            item.setAddTime(history.getAddTime());
            item.setUpdateTime(history.getUpdateTime());
            item.setAddUserName(history.getAddUserName());
            item.setUpdateUserName(history.getUpdateUserName());
            item.setId(DefaultIdGenerator.getInstance().generateLongId());
            item.setAssessmentId(assessmentId);
            items.add(item);
        }
        return items;
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        AssessmentHistoryMapper historyMapper = factory.getMapper(AssessmentHistoryMapper.class);
                        AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
                        AssessmentItemHistoryMapper itemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
                        AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);

                        AssessmentHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            history.setState(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                            Assessment assessmentOld = mapper.selectByPrimaryKey(history.getBackupId());
                            if (assessmentOld != null) {
                                mapper.deleteByPrimaryKey(assessmentOld.getId());
                                itemMapper.deleteByAssessmentId(assessmentOld.getId());
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }


    private void discardApprovalDiscard(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        AssessmentHistoryMapper historyMapper = factory.getMapper(AssessmentHistoryMapper.class);
                        AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
                        AssessmentItemHistoryMapper itemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
                        AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);

                        AssessmentHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            history.setState(4);
                            historyMapper.updateByPrimaryKeySelective(history);
                            Assessment assessmentOld = mapper.selectByPrimaryKey(history.getBackupId());
                            if (assessmentOld != null) {
                                assessmentOld.setState(0);
                                mapper.updateByPrimaryKeySelective(assessmentOld);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (audit.getOperation() == 1) {
                editApprovalDiscard(idList);
            } else if (audit.getOperation() == 2) {
                discardApprovalDiscard(idList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(AssessmentServiceImpl.class.getName(), this);
        map.put(AssessmentAuditService.class.getName(), new AssessmentAuditService());
    }


    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }

}
